<template>
  <el-select
    :loading="isFirstLoad"
    v-model="supplierName"
    filterable
    remote
    :placeholder="$t('common.placeholderSelect')"
    @change="handleChange"
    @focus="visibleChange"
    :remote-method="remoteMethod"
    clearable
  >
    <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
  </el-select>
</template>
<script>
import { SupplierList } from '@/api/money'
export default {
  props: {
    params: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      supplierName: '',
      timeout: null,
      options: [],
      pageNum: 1,
      loading: false,
      isFirstLoad: true,
      dataList: []
    }
  },
  watch: {
    value(newVal, oldVal) {
      if (oldVal == '' && newVal != '') {
        this.batchInit()
      } else if (newVal == '') {
        this.supplierName = ''
      }
    },
    batchAry(v) {
      if (v) {
        this.dataList = v
      }
    }
  },
  mounted() {
    this.batchInit()
  },
  methods: {
    batchInit() {
      if (this.batch && this.dataList.length > 0) {
        this.supplierName = this.dataList[0].name
      } else if (!!this.value) {
        this.getAntCenter(this.value)
      }
    },
    visibleChange(v) {
      if (v && this.options.length == 0) {
        this.getStores()
      }
    },
    getStores() {
      if (!this.loading) {
        this.loading = true
        SupplierList({
          pageNum: 1,
          pageSize: 10000
        })
          .then(r => {
            this.loading = false
            this.isFirstLoad = false
            if (r.data.list.length > 0) {
              // this.pageNum++
              this.options = [...this.options, ...r.data.list]
            }
          })
          .catch(e => {
            this.loading = false
            this.isFirstLoad = false
          })
      }
    },
    async remoteMethod(query) {
      this.pageNum = 1
      try {
        var data = await SupplierList({
          pageNum: this.pageNum,
          pageSize: 10000,
          name: query,
          ...this.params
        })
        this.pageNum++
        this.options = data.data.list
      } catch (error) {}
    },
    handleChange(item) {
      this.$emit(
        'change',
        this.options.filter(o => o.id == item)
      )
      this.$emit('input', item)
    },
    getAntCenter(id) {
      SupplierList({
        id
      }).then(r => {
        this.supplierName = r.data.name
      })
    }
  }
}
</script>
